﻿import net.spreadshirt.shop.lib.Producttype;

/**
 * The Producttypes class stores a list of producttypes
 * and provides some methods to handle the lists items.
 */
class net.spreadshirt.shop.lib.Producttypes {

	// A list of all product type items.
	private var _producttypes:Array;

	/**
	 * Producttypes Constructor
	 */
	public function Producttypes() {
		clear();
	}

	/**
	 * Clears all values.
	 */
	public function clear():Void {
		_producttypes = new Array();
	}

	/**
	 * Stores a list of product types.
	 * The old list will be overwritten.
	 * 
	 * @param	items	A list of article items.
	 */
	public function addProducttypes(items:Array):Void {
		for(var i:Number = 0; i < items.length; i++) {
			addProducttype(items[i]);
		}
	}

	/**
	 * Stores a single product type in the product types list.
	 * 
	 * @param	item	A product type item.
	 */
	public function addProducttype(item:Object):Void {
		// Only adds the item if there's no other item
		// with the same product type ID already stored.
		if(!isExisting(item)){
			var producttype:Producttype = new Producttype(item);
			_producttypes.push(producttype);
		}
	}

	/**
	 * Returns the number of stored product types.
	 * 
	 * @return	The number of product type items.
	 */
	public function getCount():Number {
		return _producttypes.length;
	}

	/**
	 * Returns the complete list of all product types.
	 * 
	 * @return	A list of product type items.
	 */
	public function getAllItems():Array {
		return _producttypes;
	}

	/**
	 * Returns all product type IDs of all item in the product types list.
	 * 
	 * @return	A list of product type IDs.
	 */
	public function getAllIDs():Array {
		var producttypeIDs:Array = new Array();
		for(var i:Number = 0; i < _producttypes.length; i++) {
			producttypeIDs.push(_producttypes[i].producttype_id);
		}
		return producttypeIDs;
	}

	/**
	 * Returns all product type IDs of a special category.
	 * 
	 * @return	 A list of product type IDs.
	 */
	public function getIDsByCategory(category_id:Number):Array {
		var producttypeIDs:Array = new Array();
		//############ _producttypes.length = 0!!! It shouldn't be  ###################
		trace("Producttypes.as, _producttypes.length: "+_producttypes.length);
		for(var i:Number = 0; i < _producttypes.length; i++) {
			var cid:Number = _producttypes[i].producttype_category_id;
			if(category_id == cid) {
				producttypeIDs.push(_producttypes[i].producttype_id);
			}
		}
		return producttypeIDs;
	}

	/**
	 * Checks if the product type is already stored.
	 * 
	 * @param	item	A single product type item.
	 * 
	 * @return	true or false
	 */
	private function isExisting(item:Object):Boolean {
		var found:Boolean = false;
		for(var i:Number = 0; i < _producttypes.length; i++) {
			if(item.producttype_id == _producttypes[i].producttype_id) {
				found = true;
				break;
			}
		}
		return found;
	}

}
